import { setLocalStorage } from '@/utils'
import { useEffect, useState } from 'react'
import { useModel } from 'umi'

const userPermissionsDefault = {
  id: 0,
  name: '未登录',
  userCount: 0,
  users: '未登录',
  permission: '[]',
}

interface roleListItem {
  id: number // id自增列
  name: string // 角色名称
  permission: string // 角色菜单列表
  userCount: number // 用户数量
  users: string // 角色用户列表
}

export default () => {
  // 用户数据
  const [clientId, setClientId] = useState('')
  const [userPermissions, setUserPermissions] = useState<roleListItem>(userPermissionsDefault)
  const [userName, setUserName] = useState('')

  // 初始化模组
  const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState')

  // 清空数据
  const cleanUserModel = () => {
    setClientId('')
    setUserPermissions(userPermissionsDefault)
    setUserName('')
  }

  // 初始化数据
  useEffect(() => {
    if (!loading && initialState?.models?.userModel) {
      const { clientId, userPermissions, userName } = initialState.models.userModel
      if (clientId) setClientId(clientId)
      if (userPermissions) setUserPermissions(userPermissions)
      if (userName) setUserName(userName)
    }
  }, [loading])

  // 实时保存userModel
  useEffect(() => {
    if (loading) return
    setLocalStorage('userModel', { clientId, userPermissions, userName })
  }, [clientId, userPermissions])

  // 权限更新重新初始化
  useEffect(() => {
    if (loading || userPermissions.name === '未登录') return
    refresh()
  }, [userPermissions])

  return { clientId, setClientId, setUserPermissions, cleanUserModel, userName, setUserName }
}
